package com.rytong.tools.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import com.rytong.tools.utils.Utils;
import android.app.Activity;
import android.content.Context;
import android.graphics.Paint;
import android.graphics.Rect;
import android.text.InputFilter;
import android.view.inputmethod.InputMethodManager;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.EditText;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;

//密码框控件
public class LPPasswordText extends Component {

    // 输入框限制输入类型
    final static int InputType_TYPE_CLASS_TEXT = 0;
    final static int InputType_TYPE_TEXT_VARIATION_PASSWORD = InputType_TYPE_CLASS_TEXT + 1;
    final static int InputType_TYPE_NUMBER_FLAG_DECIMAL = InputType_TYPE_TEXT_VARIATION_PASSWORD + 1;
    final static int InputType_TYPE_CLASS_NUMBER = InputType_TYPE_NUMBER_FLAG_DECIMAL + 1;
    final static int InputType_TYPE_CLASS_DATETIME = InputType_TYPE_CLASS_NUMBER + 1;
    final static int InputType_TYPE_CLASS_PHONE = InputType_TYPE_CLASS_DATETIME + 1;
    final static int InputType_TYPE_TEXT_VARIATION_VISIBLE_PASSWORD = InputType_TYPE_CLASS_PHONE + 1;
    final static int InputType_TYPE_NUMBER_ALPHABET = InputType_TYPE_TEXT_VARIATION_VISIBLE_PASSWORD + 1;
    private Context mContext;
    private LPKeyboardView keyboardView;
    String isEncrypt_;
    String attrName_;
    String attrValue_;
    boolean attrSave_;
    private InputMethodManager imm;

    public int mMax;
    public int mMin;
    // 输入框的输入限制类型
    private int mConstrain_;
    private boolean isPasswordWidget_;
    int h = 0;

    public class MyLPPasswordText extends EditText implements CompositedComponent {

        public MyLPPasswordText(Context context, String value) {
            super(context);
            mContext = context;
            int maxSize = maxLeng();
            mMax = maxSize;
            if (maxSize > 0) {
                setFilters(new InputFilter[] { new InputFilter.LengthFilter(maxSize) });
            }
            setFocusable(true);
            setFocusableInTouchMode(true);
            imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(this.getWindowToken(), 0);
            // 设置输入框的提示语言
            setHint((CharSequence) getPropertyByName("hold"));
            mConstrain_ = getConstraint(getPropertyByName("style"));
            init();
        }

        public MyLPPasswordText(Context context, boolean required, int max, int min, int constrain) {
            super(context);
            mContext = context;
            mMax = max;
            mMin = min;
            mConstrain_ = constrain;
            imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(this.getWindowToken(), 0);

            init();
        }

        @Override
        public Component composited() {
            // TODO Auto-generated method stub
            return LPPasswordText.this;
        }

        @Override
        protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
            imm.hideSoftInputFromWindow(this.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            if (focused) {                
                if (!keyboardView.isShowing()) {
                    keyboardView.showAtLocation(this, Gravity.BOTTOM, 0, 0);
                    scrollParent(h);
                    keyboardView.setOnDismissListener(new OnDismissListener() {                 
                        @Override
                        public void onDismiss() {
                            // TODO Auto-generated method stub
                            scrollParent(-h);
                        }
                    });
                }
            } else {
                if (keyboardView.isShowing()) {
                    keyboardView.dismiss();
                }
            }
            super.onFocusChanged(focused, direction, previouslyFocusedRect);
        }

        @Override
        protected void onTextChanged(CharSequence text, int start, int before, int after) {
            // TODO Auto-generated method stub
            super.onTextChanged(text, start, before, after);
            // 文本框内容发生变化时要相应更新其属性集合里的值
            if (null == property_)
                property_ = new HashMap();
            property_.put("value", getContentText());
        }

        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && keyboardView.isShowing()) {
                keyboardView.dismiss();
                return true;
            } else {
                return super.onKeyDown(keyCode, event);
            }

        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            imm.hideSoftInputFromWindow(this.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//            setInputType(InputType.TYPE_NULL);// 无焦点时屏避软键盘
            int x = (int) event.getX();
            int y = (int) event.getY();

            // 在整个屏幕中按下去的y坐标
            int aY = (int) event.getRawY();

            int viewY = 0;
            if (y > 0 && y <= this.getHeight()) {
                // 输入框下边框在屏幕中的高度
                viewY = (this.getHeight() - y) + aY;
            }

            // 判断输入框是否被密码键盘覆盖                        
            int height = keyboardView.getHeight();
            int scrollY = this.getScrollY();
            if ((SCREENHEIGHT + scrollY - viewY) < height) {
                // 被密码覆盖的高度，也就是需要向上滚动的距离
                h = Math.abs(SCREENHEIGHT + scrollY - viewY - height - this.getHeight());
            }

            int action = event.getAction();
            switch (action) {
            case MotionEvent.ACTION_DOWN:
                requestFocus();
                return true;
            case MotionEvent.ACTION_UP:
                if (!keyboardView.isShowing()) {
                    keyboardView.showAtLocation(this, Gravity.BOTTOM, 0, 0);
                    scrollParent(h);
                    keyboardView.setOnDismissListener(new OnDismissListener() {                 
                        @Override
                        public void onDismiss() {
                            // TODO Auto-generated method stub
                            scrollParent(-h);
                        }
                    });
                }
                return false;
            }
            
            if (!isEnabled()) {
                return true;
            } else {
                return super.onTouchEvent(event);
            }
        }

    }

    private void init() {
        int alertdialog_style = Utils.getResourcesId(mContext, "keyboarddialog", "style");
        if (mConstrain_ == LPPasswordText.InputType_TYPE_CLASS_NUMBER
                || mConstrain_ == LPPasswordText.InputType_TYPE_NUMBER_FLAG_DECIMAL) {
            keyboardView = new LPKeyboardView(mContext, "num", this, mMax, alertdialog_style);
        } else {
            keyboardView = new LPKeyboardView(mContext, "abc", this, mMax, alertdialog_style);
        }
        LayoutInflater inflater = LayoutInflater.from(mContext);
        int keyboard_layout = Utils.getResourcesId(mContext, "keyboard", "layout");
        View view = inflater.inflate(keyboard_layout, null);
        keyboardView.setOutsideTouchable(true);
        keyboardView.setWidth(LayoutParams.MATCH_PARENT);
        keyboardView.setHeight(LayoutParams.WRAP_CONTENT);
        keyboardView.setFocusable(false);
//        keyboardView.setCanceledOnTouchOutside(true);
        // keyboardView.setTouchable(true);
        //
        // keyboardView.setFocusable(false);

        // keyboardView.setBackgroundDrawable(new BitmapDrawable());// 点击键盘区域外，键盘消失

    }

    public void mouldH() throws Exception {
        super.mouldH();
        if (null == realView_)
            return;
        MyLPPasswordText mlppt = (MyLPPasswordText) realView_;
        Paint paint = mlppt.getPaint();
        // 设置字体或者绘制效果平滑
        paint.setAntiAlias(true);
//        if (null != cssStyle_) {
//            String bgcolor = (String) cssStyle_.getProperty(CssStyle.BACKGROUNDCOLOR);
//            int cs_bgcolor = 0;
//            // 设置背景颜色
//            if (null != bgcolor && !bgcolor.equals("")) {
//                cs_bgcolor = Utils.getColorValue(bgcolor);
//            } else {
//                // 如果后台没给返回值，将背景色设为透明
////                cs_bgcolor = 0x00000000;
//            }
//            mlppt.setBackgroundColor(cs_bgcolor);
//        }
        
        // 表示是否有边框，1表示有边框，0表示无边框，无边框的同时也无背景色（0/1）
        String border = (String) getPropertyByName("border");
        if (border.equals("0")) {
            mlppt.setBackgroundColor(0);
        }

    }

    public String getLabel() {
        String str = "";
        if (null != ((TextView) realView_).getHint()) {
            str = ((TextView) realView_).getHint().toString();
            if ((null == str) || (str.equals("")))
                str = "";
        }
        return str;
    }

    public boolean getPasswordMark() {
        return isPasswordWidget_;
    }

    // 设置密码输入框标志，如果控件是密码输入框，则该方法一定要执行
    public void setPasswordMark(boolean iswork) {
        isPasswordWidget_ = iswork;
    }

    public int getInputType() {
        // TODO Auto-generated method stub
        return mConstrain_;
    }

    @Override
    public void setCssStyle(CssStyle style) {
        cssStyle_ = style;
    }

    @Override
    public void setEncrypt(String encrypt) {
        isEncrypt_ = encrypt;
    }

    @Override
    public String getContentText() {
        StringBuffer buf = new StringBuffer();
        if (null == keyboardView)
            return "";
        ArrayList<LPKeyboardButton> buttonlist = keyboardView.buttonlist;
        for (LPKeyboardButton button : buttonlist) {
            buf.append(button.getText().toString());
        }
        String temp = buf.toString();
        buf = null;
        return temp;
    }

    @Override
    public void initRealView(Activity activity, String value) {
        // TODO Auto-generated method stub
        realView_ = new MyLPPasswordText(activity, value);
        realView_.setPadding((int) Utils.getScaledValueX(5), 0, 0, 0);
        super.initRealView(activity, value);
    }

    public int maxLeng() {
        int maxLength = 0;
        if (null != property_) {
            String maxSize = (String) property_.get("maxleng");
            if (null != maxSize) {
                maxLength = Integer.parseInt(maxSize);
            }
        }
        return maxLength;
    }

    private int getConstraint(Object style) {
        if (null != style) {
            String format = (String) style;
            int j = format.indexOf(";");
            if (j >= 0) {
                String front = format.substring(0, j).trim();
                String last = format.substring(j + 1).trim();
                if (front.indexOf("-wap-input-format") != -1) {
                    if (front.indexOf("'n'") != -1) {
                        return InputType_TYPE_NUMBER_FLAG_DECIMAL;
                    } else if (front.indexOf("'N'") != -1) {
                        return InputType_TYPE_CLASS_NUMBER;
                    } else if (front.indexOf("'date'") != -1) {
                        return InputType_TYPE_CLASS_DATETIME;
                    } else if (front.indexOf("'phone'") != -1) {
                        return InputType_TYPE_CLASS_PHONE;
                    }
                } else if (last.indexOf("-wap-input-format") != -1) {
                    if (last.indexOf("'n'") != -1) {
                        return InputType_TYPE_NUMBER_FLAG_DECIMAL;
                    } else if (last.indexOf("'N'") != -1) {
                        return InputType_TYPE_CLASS_NUMBER;
                    } else if (last.indexOf("'date'") != -1) {
                        return InputType_TYPE_CLASS_DATETIME;
                    } else if (last.indexOf("'phone'") != -1) {
                        return InputType_TYPE_CLASS_PHONE;
                    }
                }
            } else {
                if (format.indexOf("-wap-input-format") != -1) {
                    if (format.indexOf("'n'") != -1) {
                        return InputType_TYPE_NUMBER_FLAG_DECIMAL;
                    } else if (format.indexOf("'N'") != -1) {
                        return InputType_TYPE_CLASS_NUMBER;
                    } else if (format.indexOf("'date'") != -1) {
                        return InputType_TYPE_CLASS_DATETIME;
                    } else if (format.indexOf("'phone'") != -1) {
                        return InputType_TYPE_CLASS_PHONE;
                    }
                }
            }
            if (format.indexOf("-wap-code-required") != -1) {
                if (format.indexOf("'non-forbiddenCode'") != -1) {
                    return InputType_TYPE_NUMBER_ALPHABET;
                }
            }
        }
        return InputType_TYPE_CLASS_TEXT;
    }

    // 屏幕主窗口滚动，使得输入框抬升或者下降 add by chengli
    public void scrollParent(final int h) {
        // TODO Auto-generated method stub
        try {

            if (DIALOGHASH != null && DIALOGHASH.size() > 0) {
                Set set = DIALOGHASH.keySet();
                Iterator iterator = set.iterator();
                while (iterator.hasNext()) {
                    Object key = iterator.next();
                    Object valueDialog = DIALOGHASH.get(key);
                    if (valueDialog instanceof LPAlertDialog) {
                        LPAlertDialog dialog = (LPAlertDialog) valueDialog;
                        Window window = dialog.getWindow();
                        LayoutParams attributes = window.getAttributes();
                        attributes.gravity = Gravity.CENTER;
                        if (h < 0) {
                            attributes.y = 0;
                        } else {
                            attributes.y = -h;
                        }
                        attributes.x = 0;
                        window.setAttributes(attributes);
                        if (dialog.isShowing()) {
                            dialog.show();
                            // dialog.view_.scrollBy(0, h);
                            return;
                        }
                    }
                }
            }

            ((Activity) mContext).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    int size = Component.VWIDGETARRAY.size();
                    Object o = null;
                    Component view;
                    String tagName;
                    for (int i = 0; i < size; i++) {
                        o = Component.VWIDGETARRAY.get(i);
                        if (o instanceof Component) {
                            view = (Component) o;
                            tagName = (String) view.property_.get("name");
                            if (null != tagName) {
                                if ("body".equals(tagName)) {
                                    // 使得整个中间主窗口滚动h的距离，正位向上滚动，负为向下滚动
                                    if (null != view) {
                                        view.realView_.scrollBy(0, h);
                                    }
                                } else if ("llv".equals(tagName)) {

                                }
                            }
                        }
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
